package com.fruit.interceptor;

import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fruit.pojo.user.SysUser;
import com.fruit.service.user.SysUserManager;
import com.fruit.util.CustomUtil;




public class WapSecurityInterceptor extends HandlerInterceptorAdapter {
	
	@Value("${app.key}")
	private String key;
	
	@Autowired
	private SysUserManager sysUserService;
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		String signLogin = request.getParameter("sign.signLogin");
		boolean isLogin = false;
		SysUser sysUser = new SysUser();
		if (StringUtils.isNotEmpty(signLogin)){
			System.out.println("登录验证开始");
			String userId = request.getParameter("sign.userId");
			String nonce = request.getParameter("sign.nonce");
			String timestamp = request.getParameter("sign.timestamp");
			sysUser.setUserId(userId);
			sysUser = sysUserService.getUserInfo(sysUser);
			if(sysUser != null){
				Map<String, String> paramsO = new TreeMap<String, String>();
				paramsO.put("userName", sysUser.getUserName());
				paramsO.put("pwd", sysUser.getPassword());
				paramsO.put("nonce", nonce);
				paramsO.put("timestamp", timestamp);
				String mySign = CustomUtil.createSign(paramsO,key);
				System.out.println(mySign);
				if (StringUtils.equals(signLogin.toUpperCase(), mySign)) {
					isLogin = true;
				}
			}
			System.out.println("登录验证结束");
			if(isLogin){
				request.getSession().setAttribute("sysUser", sysUser);
			}
		}
		
		
		return true;
	}
	
}
